//
//  HomeViewController.m
//  Manager
//
//  Created by 彭凯敏 on 15/8/14.
//  Copyright (c) 2015年 52xiaoluo. All rights reserved.
//

#import "ViewRoomViewController.h"
#import "RoomCell.h"

#import "RoomInfoViewController.h"

#import "AddLookViewController.h"

#import "Viewroom.pb.h"
#import "ViewRoomLogic.h"
#import "ViewOrderModel.h"
#import <MJRefresh.h>
@interface ViewRoomViewController ()
{
    NSMutableArray *dataArray;
}

@property (nonatomic,strong)UITableView *tableView;

@end

@implementation ViewRoomViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createUI];
    // Do any additional setup after loading the view from its nib.    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(orderDataChanged:) name:Notifi_Order_Data object:nil];
    
    dataArray = [[NSMutableArray alloc]initWithObjects:@[],@[],@[],@[], nil];
    
    [self reloadData];
    [self queryRoomRequestOrigin];
}
- (void)createUI
{
    [self homeBaseCtlSetTitle:@"带看列表" andWithBackType:BackZero];
    
    [self baseCtlSetLeftBtnImage:[UIImage imageNamed:@"itemAdd"] andRightBtnImage:nil];
    
    [self baseCtlSetLeftBtnTitle:nil andWithRightTitle:@"查看房源"];
    
    [self.leftNavgationItem setAction:@selector(clickLook:)];
    [self.rightNavgationItem setAction:@selector(clickRoom:)];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64-49) style:UITableViewStylePlain];
    [_tableView setLineType:TableViewLineTypeAll];
    _tableView .delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    
    __weak __typeof(self) weakSelf = self;

    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf queryRoomRequestOrigin];
    }];
    
    
}

#pragma mark - request
- (void)queryRoomRequestOrigin
{
    QueryOrderReqBuilder *builder = [[QueryOrderReqBuilder alloc]init];
    [builder setStatus:@"4"];
    
    [[ViewRoomLogic shareInstance]queryOrderReqWithBuild:builder.build];
    
}

- (void)orderDataChanged:(NSNotification *)noti
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [_tableView.header endRefreshing];
        if (noti.object == nil) {
         return ;   
        }
        else if ([noti.object isKindOfClass:[ErrorModel class]]) {
            
            ErrorModel *model = noti.object;
            [UIViewCategory FailShowWith:model];
            return ;
        }
        else
        {
            NSString *status = noti.object;
            if ([status isEqualToString:@"4"]) {
                [self reloadData];
            }
        }
    });
}

-(void) reloadData {
    NSArray *data = [[ViewRoomLogic shareInstance] getOrdeModelArrayByStatus:@"4"];
    [dataArray setArray:[self judgeDateWith:data]];
    
    [_tableView reloadRoomAndisNil:dataArray nitText:@"当前无看房信息"];
    
}

#pragma mark - 时间分组
- (NSArray *)judgeDateWith:(NSArray *)array
{
    NSMutableArray *array0 = [NSMutableArray array];//超期
    NSMutableArray *array1 = [NSMutableArray array];//今天
    NSMutableArray *array2 = [NSMutableArray array];//明天
    NSMutableArray *array3 = [NSMutableArray array];//明后
    
    
    [KMGetDate timeFromNum:@""];
    
    for (ViewOrderModel *model in array) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:model.order.viewTime/1000];
        
        if ([self compareDate:date] == 0) {
            [array0 addObject:model];
        }
        else if ([self compareDate:date] == 1) {
            [array1 addObject:model];
        }
        else if ([self compareDate:date] == 2) {
            [array2 addObject:model];
        }
        else if ([self compareDate:date] == 3) {
            [array3 addObject:model];
            
        }
    }
    array = @[array0,array1,array2,array3];
    
    return array;
}
-(NSInteger)compareDate:(NSDate *)date{
    
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *today = [[NSDate alloc] init];
    NSDate *tomorrow;
    
    tomorrow = [today dateByAddingTimeInterval:secondsPerDay];
    
    // 10 first characters of description is the calendar date:
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"YYYYMMdd"];
    
    NSString * todayString = [[formatter1 stringFromDate:today] substringToIndex:8];
    NSString * tomorrowString = [[formatter1 stringFromDate:tomorrow] substringToIndex:8];
    
    NSString * dateString = [[formatter1 stringFromDate:date] substringToIndex:8];

    
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
    [formatter2 setDateFormat:@"YYYYMMddHHmm"];
    NSString * nowString = [[formatter2 stringFromDate:today] substringToIndex:12];
    NSString * dateString2 = [[formatter2 stringFromDate:date] substringToIndex:12];
    
    if ([dateString2 longLongValue]<[nowString longLongValue])
    {
        return 0;
    }
    else if ([dateString isEqualToString:todayString])
    {
        return 1;
    }else if ([dateString isEqualToString:tomorrowString])
    {
        return 2;
    }
    else if([dateString longLongValue]>[tomorrowString longLongValue])
    {
        return 3;
    }
    else
    {
        return 0;
    }
}



#pragma mark - events


- (void)clickLook:(UIBarButtonItem *)item
{
    AddLookViewController *vc = [[AddLookViewController alloc]initWithNibName:IS320? @"AddLookViewController_5":@"AddLookViewController_6" bundle:nil];
    HideTabbar(vc);
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)clickRoom:(UIBarButtonItem *)item
{
    WebViewController *web = [[WebViewController alloc]init];
    web.urlStr = @"http://180.150.186.187/show/public/Room/list?src=preview";
    HideTabbar(web);
    [self.navigationController pushViewController:web animated:YES];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    RoomInfoViewController *info = [[RoomInfoViewController   alloc]init];
    HideTabbar(info);
    ViewOrderModel *model = dataArray[indexPath.section][indexPath.row];

    info.orderInfo = model.order;
    
    [self.navigationController pushViewController:info animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//    return 44;
    return ((NSArray *)dataArray[section]).count == 0?0:44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    view.tag=section+10;
    view.backgroundColor = RGB(145,182,240,1);
    
    NSArray *array = dataArray[section];
    
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(9, 0, 100, 44)];
    if (section == 0) {
        titleLabel.text = [NSString stringWithFormat:@"超期的任务(%lu)",(unsigned long)array.count];
    }
    else if (section == 1) {
        titleLabel.text = [NSString stringWithFormat:@"今天(%lu)",(unsigned long)array.count];
    }
    else if (section == 2) {
        titleLabel.text = [NSString stringWithFormat:@"明天(%lu)",(unsigned long)array.count];
    }
    else if (section == 3) {
        titleLabel.text = [NSString stringWithFormat:@"明后(%lu)",(unsigned long)array.count];
    }
    
    titleLabel.font = [UIFont boldSystemFontOfSize:14];
    
    titleLabel.textColor = [UIColor whiteColor];
    [view addSubview:titleLabel];
    
    return view;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return ((NSArray *)dataArray[section]).count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"RoomCell";
    RoomCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell)
    {
        [tableView registerNib:[UINib nibWithNibName:@"RoomCell_6" bundle:nil] forCellReuseIdentifier:CellIdentifier];

        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
    }
    
        ViewOrderModel *model = dataArray[indexPath.section][indexPath.row];
    
    [cell setCellOrder:model.order];
    
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 176;
    
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
#ifdef __IPHONE_8_0
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
#endif
    
    
}



@end
